package com.forum.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import com.forum.model.dao.SectionDAO;
import com.forum.model.dao.TopicDAO;
import com.forum.model.pojo.Section;

@WebFilter("/section.jsp")
public class SectionFilter implements Filter {
	public void init(FilterConfig fConfig) throws ServletException {
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String sectionName = request.getParameter("name");
		
		if(sectionName != null){
			Section sect = new SectionDAO().getObjectById(sectionName);
			sect.setTopics(new TopicDAO().getAll(sectionName));
			
			if(sect != null){
				request.setAttribute("section", sect);
				chain.doFilter(request, response);
				return;
			}
		}
		
		RequestDispatcher disapatcher = request.getRequestDispatcher("/index.jsp");
		disapatcher.forward(request, response);
	}
}